﻿using System;
using System.Collections.Generic;
using System.Text;
using Fsb.Utility;

namespace VideoCache.Spider.FileFetchers
{
    class FlvCDFetcher : IFetcher
    {
        const string PARSER_URL = "http://www.flvcd.com/parse.php?kw={0}&flag=one&format={1}";

        public FetcherResult[] GetFiles(string url)
        {
            List<FetcherResult> list = new List<FetcherResult>();

            string normalHtml = this.GetHtml(url, "normal");

            FetcherResult normalResult = this.GetResolutionFiles(normalHtml);
            if (normalResult != null)
            {
                normalResult.Resolution = Resolution.Level_1;
                list.Add(normalResult);
            }

            string[] resolutionUrl = this.GetResolutions(normalHtml);

            if (resolutionUrl != null)
            {
                for (int i = 0; i < resolutionUrl.Length; i++)
                {
                    string query = resolutionUrl[i].Substring(resolutionUrl[i].IndexOf("?") + 1);

                    string[] paramList = query.Split('&');

                    string format = string.Empty;
                    foreach (string param in paramList)
                    {
                        if (param.ToLower().StartsWith("format="))
                        {
                            string[] sep = param.Split('=');
                            if (sep.Length == 2) format = sep[1];
                            break;
                        }
                    }

                    if (!string.IsNullOrEmpty(format))
                    {
                        string html = this.GetHtml(url, format);
                        FetcherResult result = this.GetResolutionFiles(html);
                        if (result != null)
                        {
                            switch (format)
                            {
                                case "normal":
                                    result.Resolution = Resolution.Level_1;
                                    break;
                                case "high":
                                    result.Resolution = Resolution.Level_2;
                                    break;
                                case "super":
                                    result.Resolution = Resolution.Level_3;
                                    break;
                            }

                            list.Add(result);
                        }
                    }
                }
            }

            if (list.Count == 0)
            {
                throw new FetcherException("无法获取视频下载地址，视频不存在或已删除。");
            }

            return list.ToArray();
        }

        private string GetHtml(string url, string format)
        {
            return HttpUtility.Get(string.Format(PARSER_URL, HttpUtility.UrlEncode(url, Encoding.GetEncoding("gb2312")), format), Encoding.GetEncoding("gb2312"));
        }

        private string[] GetResolutions(string html)
        {
            string content = StringUtility.SubString(html, "用硕鼠下载该视频", "</td>");

            if (string.IsNullOrEmpty(content)) return null;

            List<string> list = new List<string>();

            string[] anchorList = content.Split(new string[] { "<a " }, StringSplitOptions.RemoveEmptyEntries);

            for (int i = 1; i < anchorList.Length; i++)
            {
                string url = StringUtility.SubString(anchorList[i], "href=\"", "\"");
                if (!string.IsNullOrEmpty(url) && url.ToLower().IndexOf("flag=one") != -1)
                {
                    list.Add(url);
                }
            }

            return list.ToArray();
        }

        private FetcherResult GetResolutionFiles(string html)
        {
            html = StringUtility.SubString(html, "下载地址：", "</td>");
            string[] list = html.Split(new string[] { "<a " }, StringSplitOptions.RemoveEmptyEntries);

            if (list == null) return null;

            FetcherResult result = new FetcherResult();
            for (int i = 1; i < list.Length; i++)
            {
                string url = StringUtility.SubString(list[i], "href=\"", "\"");

                if (!string.IsNullOrEmpty(url))
                {
                    result.Files.Add(url);
                }
            }

            return result;
        }
    }
}
